<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选课管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .search-box {
            display: flex;
            width: 300px;
        }

        .search-box input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            outline: none;
        }

        .search-box button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        .add-button {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #333;
        }

        tr:hover {
            background-color: #f5f7f9;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .edit-button,
        .delete-button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .edit-button {
            background-color: #3498db;
            color: white;
        }

        .delete-button {
            background-color: #e74c3c;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 50%;
            max-width: 500px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-cancel,
        .btn-save {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-cancel {
            background-color: #f1f1f1;
            color: #333;
        }

        .btn-save {
            background-color: #2ecc71;
            color: white;
        }

        .filter-section {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: flex-end;
        }

        .filter-item {
            flex: 1;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li><a href="/admin/teachers">教师管理</a></li>
                <li><a href="/admin/students">学生管理</a></li>
                <li><a href="/admin/courses">课程管理</a></li>
                <li><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li class="active"><a href="/admin/course-selections">选课管理</a></li>
                <li><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>选课管理</h1>
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索学生ID或姓名...">
                    <button type="button" onclick="searchCourseSelections()">搜索</button>
                </div>
                <button class="add-button" onclick="openAddModal()">添加选课记录</button>
            </div>

            <div class="filter-section">
                <div class="filter-item">
                    <label for="studentFilter">按学生筛选</label>
                    <select id="studentFilter" onchange="filterByStudent()">
                        <option value="">所有学生</option>
                        <!-- 学生选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="filter-item">
                    <label for="courseFilter">按课程筛选</label>
                    <select id="courseFilter" onchange="filterByCourse()">
                        <option value="">所有课程</option>
                        <!-- 课程选项将通过JavaScript动态加载 -->
                    </select>
                </div>
            </div>

            <table id="courseSelectionsTable">
                <thead>
                    <tr>
                        <th>选课ID</th>
                        <th>学生ID</th>
                        <th>学生姓名</th>
                        <th>课程ID</th>
                        <th>课程名称</th>
                        <th>学年</th>
                        <th>学期</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="courseSelectionsList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加选课记录模态框 -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddModal()">&times;</span>
            <h2>添加选课记录</h2>
            <div class="form-group">
                <label for="addStudentId">学生</label>
                <select id="addStudentId" name="studentId">
                    <!-- 学生选项将通过JavaScript动态加载 -->
                </select>
            </div>
            <div class="form-group">
                <label for="addCourseId">课程</label>
                <select id="addCourseId" name="courseId">
                    <!-- 课程选项将通过JavaScript动态加载 -->
                </select>
            </div>
            <div class="form-group">
                <label for="addStatus">状态</label>
                <select id="addStatus" name="status" onchange="toggleAddScoreField()">
                    <option value="未修">未修</option>
                    <option value="正在修">正在修</option>
                    <option value="已修">已修</option>
                </select>
            </div>
            <div class="form-group" id="addScoreGroup" style="display: none;">
                <label for="addScore">成绩</label>
                <input type="number" id="addScore" name="score" min="0" max="100" step="0.01">
            </div>
            <div class="form-group">
                <label for="addYear">学年</label>
                <input type="number" id="addYear" name="year" min="2000" max="2100">
            </div>
            <div class="form-group">
                <label for="addSemester">学期</label>
                <select id="addSemester" name="semester">
                    <option value="大一上">大一上</option>
                    <option value="大一下">大一下</option>
                    <option value="大二上">大二上</option>
                    <option value="大二下">大二下</option>
                    <option value="大三上">大三上</option>
                    <option value="大三下">大三下</option>
                    <option value="大四上">大四上</option>
                    <option value="大四下">大四下</option>
                </select>
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeAddModal()">取消</button>
                <button class="btn-save" onclick="addCourseSelection()">保存</button>
            </div>
        </div>
    </div>

    <!-- 编辑选课记录模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>编辑选课记录</h2>
            <input type="hidden" id="editSelectionId">
            <div class="form-group">
                <label for="editStudentId">学生</label>
                <select id="editStudentId" name="studentId">
                    <!-- 学生选项将通过JavaScript动态加载 -->
                </select>
            </div>
            <div class="form-group">
                <label for="editCourseId">课程</label>
                <select id="editCourseId" name="courseId">
                    <!-- 课程选项将通过JavaScript动态加载 -->
                </select>
            </div>
            <div class="form-group">
                <label for="editStatus">状态</label>
                <select id="editStatus" name="status" onchange="toggleScoreField()">
                    <option value="未修">未修</option>
                    <option value="正在修">正在修</option>
                    <option value="已修">已修</option>
                </select>
            </div>
            <div class="form-group" id="editScoreGroup" style="display: none;">
                <label for="editScore">成绩</label>
                <input type="number" id="editScore" name="score" min="0" max="100" step="0.01">
            </div>
            <div class="form-group">
                <label for="editYear">学年</label>
                <input type="number" id="editYear" name="year" min="2000" max="2100">
            </div>
            <div class="form-group">
                <label for="editSemester">学期</label>
                <select id="editSemester" name="semester">
                    <option value="大一上">大一上</option>
                    <option value="大一下">大一下</option>
                    <option value="大二上">大二上</option>
                    <option value="大二下">大二下</option>
                    <option value="大三上">大三上</option>
                    <option value="大三下">大三下</option>
                    <option value="大四上">大四上</option>
                    <option value="大四下">大四下</option>
                </select>
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeEditModal()">取消</button>
                <button class="btn-save" onclick="updateCourseSelection()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时获取所有选课记录
        document.addEventListener('DOMContentLoaded', function () {
            fetchCourseSelections();
            fetchStudents();
            fetchCourses();
        });

        // 获取所有选课记录
        function fetchCourseSelections() {
            fetch('/api/admin/course-selections')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取选课记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    renderCourseSelectionList(data);
                })
                .catch(error => {
                    console.error('获取选课记录出错:', error);
                });
        }

        // 获取所有学生
        function fetchStudents() {
            fetch('/api/admin/students')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取学生失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    populateStudentOptions(data);
                })
                .catch(error => {
                    console.error('获取学生出错:', error);
                });
        }

        // 获取所有课程
        function fetchCourses() {
            fetch('/api/admin/courses')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取课程失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    populateCourseOptions(data);
                })
                .catch(error => {
                    console.error('获取课程出错:', error);
                });
        }

        // 填充学生选项
        function populateStudentOptions(students) {
            const studentFilter = document.getElementById('studentFilter');
            const addStudentSelect = document.getElementById('addStudentId');
            const editStudentSelect = document.getElementById('editStudentId');

            // 清空现有选项（保留第一个"所有学生"选项）
            studentFilter.innerHTML = '<option value="">所有学生</option>';
            addStudentSelect.innerHTML = '<option value="">--选择学生--</option>';
            editStudentSelect.innerHTML = '<option value="">--选择学生--</option>';

            students.forEach(student => {
                const option = document.createElement('option');
                option.value = student.studentId;
                option.textContent = `${student.name} (${student.studentId})`;

                studentFilter.appendChild(option.cloneNode(true));
                addStudentSelect.appendChild(option.cloneNode(true));
                editStudentSelect.appendChild(option);
            });
        }

        // 填充课程选项
        function populateCourseOptions(courses) {
            const courseFilter = document.getElementById('courseFilter');
            const addCourseSelect = document.getElementById('addCourseId');
            const editCourseSelect = document.getElementById('editCourseId');

            // 清空现有选项（保留第一个"所有课程"选项）
            courseFilter.innerHTML = '<option value="">所有课程</option>';
            addCourseSelect.innerHTML = '<option value="">--选择课程--</option>';
            editCourseSelect.innerHTML = '<option value="">--选择课程--</option>';

            courses.forEach(course => {
                const option = document.createElement('option');
                option.value = course.courseId;
                option.textContent = `${course.name} (${course.courseId})`;

                courseFilter.appendChild(option.cloneNode(true));
                addCourseSelect.appendChild(option.cloneNode(true));
                editCourseSelect.appendChild(option);
            });
        }

        // 渲染选课记录列表
        function renderCourseSelectionList(courseSelections) {
            const tableBody = document.getElementById('courseSelectionsList');
            tableBody.innerHTML = '';

            if (courseSelections.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="9" style="text-align: center;">没有找到选课记录</td>';
                tableBody.appendChild(emptyRow);
                return;
            }

            courseSelections.forEach(selection => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${selection.selectionId}</td>
                    <td>${selection.studentId}</td>
                    <td>${selection.student ? selection.student.name : '未知'}</td>
                    <td>${selection.courseId}</td>
                    <td>${selection.course ? selection.course.name : '未知'}</td>
                    <td>${selection.year}</td>
                    <td>${selection.semester}</td>
                    <td>${selection.status}</td>
                    <td class="actions">
                        <button class="edit-button" onclick="openEditModal(${selection.selectionId}); return false;">编辑</button>
                        <button class="delete-button" onclick="confirmDelete(${selection.selectionId}); return false;">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 搜索选课记录
        function searchCourseSelections() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (searchTerm === '') {
                fetchCourseSelections();
                return;
            }

            fetch(`/api/admin/course-selections/search?term=${encodeURIComponent(searchTerm)}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('搜索选课记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    renderCourseSelectionList(data);
                })
                .catch(error => {
                    console.error('搜索选课记录出错:', error);
                });
        }

        // 按学生筛选
        function filterByStudent() {
            const studentId = document.getElementById('studentFilter').value;
            if (studentId === '') {
                fetchCourseSelections();
                return;
            }

            fetch(`/api/admin/course-selections/search?studentId=${encodeURIComponent(studentId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('筛选选课记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    renderCourseSelectionList(data);
                })
                .catch(error => {
                    console.error('筛选选课记录出错:', error);
                });
        }

        // 按课程筛选
        function filterByCourse() {
            const courseId = document.getElementById('courseFilter').value;
            if (courseId === '') {
                fetchCourseSelections();
                return;
            }

            fetch(`/api/admin/course-selections/search?courseId=${encodeURIComponent(courseId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('筛选选课记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    renderCourseSelectionList(data);
                })
                .catch(error => {
                    console.error('筛选选课记录出错:', error);
                });
        }

        // 根据状态显示或隐藏添加模态框的成绩字段
        function toggleAddScoreField() {
            const status = document.getElementById('addStatus').value;
            const scoreGroup = document.getElementById('addScoreGroup');

            if (status === '已修') {
                scoreGroup.style.display = 'block';
            } else {
                scoreGroup.style.display = 'none';
                document.getElementById('addScore').value = '';
            }
        }

        // 打开添加选课记录模态框
        function openAddModal() {
            document.getElementById('addModal').style.display = 'block';
            // 设置默认值
            const currentYear = new Date().getFullYear();
            document.getElementById('addYear').value = currentYear;
            document.getElementById('addStatus').value = '正在修';
            // 根据默认状态设置成绩字段的可见性
            toggleAddScoreField();
        }

        // 关闭添加选课记录模态框
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // 添加选课记录
        function addCourseSelection() {
            const studentId = document.getElementById('addStudentId').value;
            const courseId = document.getElementById('addCourseId').value;
            const status = document.getElementById('addStatus').value;
            const year = document.getElementById('addYear').value;
            const semester = document.getElementById('addSemester').value;
            const score = document.getElementById('addScore').value;

            // 简单验证
            if (!studentId || !courseId || !year || !semester) {
                alert('请填写所有必填字段');
                return;
            }

            // 检查"已修"状态是否有成绩
            if (status === '已修' && (!score || score.trim() === '')) {
                alert('状态为"已修"时，必须填写成绩');
                return;
            }

            const selectionData = {
                studentId: studentId,
                courseId: courseId,
                status: status,
                year: parseInt(year),
                semester: semester,
                score: status === '已修' ? parseFloat(score) : null
            };

            fetch('/api/admin/course-selections', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectionData)
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 409) {
                            alert('该学生已选过此课程');
                        }
                        return response.text().then(text => { throw new Error(text || '添加选课记录失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    alert('添加选课记录成功');
                    closeAddModal();
                    fetchCourseSelections();
                })
                .catch(error => {
                    console.error('添加选课记录出错:', error);
                });
        }

        // 打开编辑选课记录模态框
        function openEditModal(selectionId) {
            console.log("Opening edit modal for selection ID:", selectionId);

            fetch(`/api/admin/course-selections/${selectionId}`)
                .then(response => {
                    console.log("Edit fetch response status:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('选课记录不存在');
                        }
                        throw new Error('获取选课记录详情失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(selection => {
                    console.log("Received selection data:", selection);

                    document.getElementById('editSelectionId').value = selection.selectionId;
                    document.getElementById('editStudentId').value = selection.studentId;
                    document.getElementById('editCourseId').value = selection.courseId;
                    document.getElementById('editStatus').value = selection.status;
                    document.getElementById('editYear').value = selection.year;
                    document.getElementById('editSemester').value = selection.semester;

                    // Set score if available
                    if (selection.score !== null) {
                        document.getElementById('editScore').value = selection.score;
                    } else {
                        document.getElementById('editScore').value = '';
                    }

                    // Toggle score field visibility based on status
                    toggleScoreField();

                    // Make sure the modal is visible with !important flag
                    const modal = document.getElementById('editModal');
                    modal.style.cssText = "display: block !important";
                })
                .catch(error => {
                    console.error('获取选课记录详情出错:', error);
                    alert('获取选课记录详情出错: ' + error.message);
                });
        }

        // 根据状态显示或隐藏成绩字段
        function toggleScoreField() {
            const status = document.getElementById('editStatus').value;
            const scoreGroup = document.getElementById('editScoreGroup');

            if (status === '已修') {
                scoreGroup.style.display = 'block';
            } else {
                scoreGroup.style.display = 'none';
                document.getElementById('editScore').value = '';
            }
        }

        // 关闭编辑选课记录模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新选课记录
        function updateCourseSelection() {
            const selectionId = document.getElementById('editSelectionId').value;
            const studentId = document.getElementById('editStudentId').value;
            const courseId = document.getElementById('editCourseId').value;
            const status = document.getElementById('editStatus').value;
            const year = document.getElementById('editYear').value;
            const semester = document.getElementById('editSemester').value;
            const score = document.getElementById('editScore').value;

            // 简单验证
            if (!studentId || !courseId || !year || !semester) {
                alert('请填写所有必填字段');
                return;
            }

            // 检查"已修"状态是否有成绩
            if (status === '已修' && (!score || score.trim() === '')) {
                alert('状态为"已修"时，必须填写成绩');
                return;
            }

            // 修改为后端期望的数据格式
            const selectionData = {
                studentId: studentId,
                courseId: courseId,
                status: status,
                year: parseInt(year),
                semester: semester,
                score: status === '已修' ? parseFloat(score) : null
            };

            console.log("Sending update data:", selectionData, "to ID:", selectionId);

            fetch(`/api/admin/course-selections/${selectionId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectionData)
            })
                .then(response => {
                    console.log("Update response status:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('选课记录不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '更新选课记录失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("Update successful, received data:", data);
                    alert('更新选课记录成功');
                    closeEditModal();
                    fetchCourseSelections();
                })
                .catch(error => {
                    console.error('更新选课记录出错:', error);
                    alert('更新选课记录失败: ' + error.message);
                });
        }

        // 确认删除选课记录
        function confirmDelete(selectionId) {
            if (confirm('确定要删除这条选课记录吗？此操作不可撤销。')) {
                deleteCourseSelection(selectionId);
            }
        }

        // 删除选课记录
        function deleteCourseSelection(selectionId) {
            fetch(`/api/admin/course-selections/${selectionId}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('选课记录不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '删除选课记录失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    alert('删除选课记录成功');
                    fetchCourseSelections();
                })
                .catch(error => {
                    console.error('删除选课记录出错:', error);
                });
        }
    </script>
</body>

</html>